package com.zime.login.dao;

import com.zime.login.domain.User;
import com.zime.login.util.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UserDao {
    /**
     *登录方法
     * @param loginUser 只有用户名和密码
     * @return user包含用户全部数据，没有查询到，返回null
      */
    public User login(User loginUser){
        User user=null;
        //连接数据库判断是否登录成功
        Connection conn=null;
        Statement stmt=null;
        ResultSet rs=null;
        //1、获取连接
        try{
            conn= JDBCUtils.getConnection();
            //2、定义sql
            //1' or '1' ='1
            //password='1' or '1'='1'
            String sql="select * from user where username= ' " + loginUser.getUsername() + " 'and password= '"+loginUser.getPassword() + "'";
            System.out.println(sql);
            //3.获取执行sql的对象
            stmt = conn.createStatement();
            //4.执行查询
            rs=stmt.executeQuery(sql);
            //5、判断
            if(rs.next()){
                int id=rs.getInt("id");
                String username=rs.getString("username");
                String password=rs.getString("password");
                user=new User();
                user.setId(id);
                user.setUsername(username);
                user.setPassword(password);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,stmt,conn);
        }
        return user;
    }
}
